package com.docMan.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.FutureTask;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.docMan.bean.DeleteFtpFileRunnable;
import com.docMan.bean.DeleteIndexRunnable;
import com.docMan.bean.FileMoverRunnable;
import com.docMan.bean.IndexFile;
import com.docMan.bean.IndexRunnable;
import com.docMan.bean.UpdateDirRunnable;
import com.docMan.bean.UpdateDiskRunnable;
import com.docMan.dao.BaseDao;
import com.docMan.dao.pojo.Dangan;
import com.docMan.dao.pojo.DocBookSon;
import com.docMan.dao.pojo.DocDirectory;
import com.docMan.dao.pojo.DocDirectoryRange;
import com.docMan.dao.pojo.DocDisc;
import com.docMan.dao.pojo.DocFile;
import com.docMan.dao.pojo.DocFtp;
import com.docMan.lucene.Searcher;
import com.docMan.service.DangAnFromOaService;
import com.docMan.service.DocBookSonService;
import com.docMan.service.DocDirectoryRangeService;
import com.docMan.service.DocDirectoryService;
import com.docMan.service.DocDiscService;
import com.docMan.service.DocFileService;
import com.docMan.utils.CastUtil;
import com.docMan.utils.FileIndexService;
import com.docMan.utils.FileMoveService;
import com.docMan.utils.FinalConfig;
import com.docMan.utils.FtpUtils;
import com.docMan.utils.GetRealPath;
import com.docMan.utils.ProjectUtils;
import com.docMan.utils.ProperiesUtils;

@Service("docFileService")
public class DocFileServiceImpl extends BaseServiceImpl<DocFile> implements
		DocFileService {
	private FileMoveService fileMoveService = FileMoveService.getInstance();
	private DocDiscService docDiscService;
	private DocDirectoryService docDirectoryService;
	private FileIndexService fileIndexService = FileIndexService.getInstance();
	private DocDirectoryRangeService docDirectoryRangeService;
	private HttpSession session;
	private DangAnFromOaService danganFromOaService;
	@Resource
	private DocBookSonService docBookSonService;
	
	@Autowired
	public void setDanganFromOaService(DangAnFromOaService danganFromOaService) {
		this.danganFromOaService = danganFromOaService;
	}

	@Autowired
	public void setDocDirectoryRangeService(
			DocDirectoryRangeService docDirectoryRangeService) {
		this.docDirectoryRangeService = docDirectoryRangeService;
	}

	@Autowired
	public void setSession(HttpSession session) {
		this.session = session;
	}

	@Resource
	public void setDocDiscService(DocDiscService docDiscService) {
		this.docDiscService = docDiscService;
	}

	@Resource
	public void setDocDirectoryService(DocDirectoryService docDirectoryService) {
		this.docDirectoryService = docDirectoryService;
	}

	@Resource(name = "docFileDao")
	@Override
	public void setDao(BaseDao<DocFile> dao) {
		super.setDao(dao);
	}

	@Override
	public String getFile(DocFile docFile) {
		List<DocFile> docFiles = find("select f from DocFile f");
		putSuccess();
		put("data", docFiles);

		return getMap();
	}

	@Override
	public String saveOrUpdateFile(DocFile docFile) {
		if (docFile.getId() <= 0 || docFile == null) {
			docFile.setHumanId(678);
			docFile.setHumanName("潘善亮");
			docFile.setLarge(0.0);
			docFile.setCreateTime(new Timestamp(System.currentTimeMillis()));
			docFile.setDisplayFileName(docFile.getFileName());
			saveOrUpdate(docFile);
			put("file", docFile);
		} else {
			DocFile docFileO = getById(docFile.getId());
			docFileO.setFileName(docFile.getFileName());
			saveOrUpdate(docFileO);
			put("file", docFile);
		}
		return getMap();
	}

	@Override
	public String createFiles(List<String> filePaths, List<String> fileSizes,
			int id, int type) {
		DocDirectory docDirectory = null;
		if (CastUtil.castBoolean(session
				.getAttribute(FinalConfig.canUploadFile2Dir))) {
			List<DocFile> docFiles = new ArrayList<DocFile>();
			String filePathInFtp = getFilePathInFtp(id, type);
			/*
			 * if(type==FinalConfig.FILE_IN_DIRECTORY)
			 * updateDirectoryWhenAddFiles(fileSizes,id);
			 */
			for (int i = 0; i < filePaths.size(); i++) {
				DocFile docFile = new DocFile();
				docFile.setFileName(getFileName(filePaths.get(i)));
				docFile.setLarge(getFileLarge(fileSizes.get(i)));
				docFile.setHumanId(Integer.parseInt(session.getAttribute(
						FinalConfig.SESSION_HUMANID).toString()));
				docFile.setHumanName(session.getAttribute(
						FinalConfig.SESSION_HUMANNAME).toString());
				docFile.setImgClass(getImgClass(filePaths.get(i)));
				docFile.setDisplayFileName(getFileName(filePaths.get(i)));
				if (type == FinalConfig.FILE_IN_DIRECTORY) {
					docDirectory = docDirectoryService.getById(id);
					docFile.setDirectoryId(id);
				} else {
					docFile.setDiskId(id);
				}
				docFile.setPath(filePathInFtp);
				docFile.setCreateTime(new Timestamp(System.currentTimeMillis()));
				docFiles.add(docFile);
			}
			saveOrUpdateAll(docFiles);
			for (int i = 0; i < docFiles.size(); i++) {
				FutureTask<Boolean> fileMoveTask = new FutureTask<>(
						new FileMoverRunnable(FinalConfig.getDocFtp(),
								filePaths.get(i), filePathInFtp));
				fileMoveService.move(fileMoveTask);
				IndexFile indexFile = new IndexFile(filePaths.get(i), docFiles
						.get(i).getPath(), docFiles.get(i).getId().toString(),
						docFiles.get(i).getHumanName(),
						ProjectUtils.timeStamp2String(docFiles.get(i)
								.getCreateTime()), docFiles.get(i)
								.getFileName(), docFiles.get(i).getImgClass());
				indexFile.setDate(new java.sql.Date(docFiles.get(i)
						.getCreateTime().getTime()));
				indexFile = setIndexFileSearchAble(indexFile, type,
						docDirectory, id);
				fileIndexService.index(new IndexRunnable(indexFile));
				// fileIndexService.indexFile(new IndexFile(filePaths.get(i),
				// docFiles.get(i).getId()));
				// TODO 确保文件搬移时发生错误能被通知到
			}
			updateParentsDirectoryWhenAddFiles(fileSizes, id, type);
			putSuccess();
			put("files", docFiles);
		} else {
			putFalse();
			putMessage("只能在自己的网盘中上传文件和新建文件夹");
		}
		return getMap();
	}

	/**
	 * 自己上传的文件夹，在建立索引的时候要根据所在文件夹的可搜索范围来设置文件索引的可搜索范围 如果文件夹的搜索范围是
	 * 部门，那么文件的searchable 字段是2，表示是部门，那么还需设置unitId的值 如果 自定义，那么文件的
	 * 3，表示某几个人可见，需设置humanIds的值
	 * 
	 * @param indexFile
	 *            索引对象
	 * @param uploadType
	 *            上传类型，上传到文件夹还是到网盘
	 * @param docDirectory
	 * @param directoryId
	 *            diskid或者是directoryId 根据uploadType
	 * @return
	 */
	private IndexFile setIndexFileSearchAble(IndexFile indexFile,
			int uploadType, DocDirectory docDirectory, int directoryId) {
		if (uploadType == FinalConfig.FILE_IN_DIRECTORY) {
			indexFile.setSearchAble(docDirectory.getDisplayRange());
			if (docDirectory.getDisplayRange().equals(
					FinalConfig.DirectoryDisplayRange_UNIT)) {
				indexFile.setUnitId(CastUtil.castString(session
						.getAttribute(FinalConfig.SESSION_HUMAN_UNIT_ID)));
			} else if (docDirectory.getDisplayRange().equals(
					FinalConfig.DirectoryDisplayRange_HUMANS)) {
				List<DocDirectoryRange> docDirectoryRanges = docDirectoryRangeService
						.find("select r from DocDirectoryRange r where r.id.directoryId=?",
								directoryId);
				StringBuilder humanIds = new StringBuilder();
				for (DocDirectoryRange docDirectoryRange : docDirectoryRanges) {
					humanIds.append("["
							+ docDirectoryRange.getId().getHumanId() + "],");
				}
				indexFile.setHumanIds(humanIds.toString());
			}
		} else if (uploadType == FinalConfig.FILE_IN_DISK) {
			indexFile.setSearchAble("1");
		}
		return indexFile;
	}

	/**
	 * 创建文件时，更新文件夹中文件的数量和占用空间大小
	 * 
	 * @param fileSizes
	 * @param id
	 */
	@SuppressWarnings("unused")
	private void updateDirectoryWhenAddFiles(List<String> fileSizes, int id) {
		DocDirectory docDirectory = docDirectoryService.getById(id);
		double directoryFileSize = docDirectory.getLarge();
		for (String string : fileSizes) {
			directoryFileSize += getFileLarge(string);
		}
		docDirectory.setLarge(directoryFileSize);
		docDirectory.setFileCount(docDirectory.getFileCount()
				+ fileSizes.size());
		docDirectoryService.update(docDirectory);
	}

	/**
	 * 在创建文件时 对文件路径上的所有文件夹和网盘的信息进行更新
	 * 
	 * @param fileSizes
	 * @param id
	 * @param type
	 *            FinalConfig.FILE_IN_DIRECTORY
	 */
	public void updateParentsDirectoryWhenAddFiles(List<String> fileSizes,
			int id, int type) {
		double directoryFileSize = 0.0;
		for (String string : fileSizes) {
			directoryFileSize += getFileLarge(string);
		}
		// 上传文件到文件夹
		if (type == FinalConfig.FILE_IN_DIRECTORY) {
			DocDirectory docDirectory = docDirectoryService.getById(id);
			fileIndexService.updateDirectory(new UpdateDirRunnable(id,
					fileSizes.size(), 0, directoryFileSize));
			String pathId = docDirectory.getPath();
			String[] ids = pathId.split("/");
			if (ids.length >= 2) {
				fileIndexService.updateDisk(new UpdateDiskRunnable(Integer
						.parseInt(ids[0]), directoryFileSize));
				for (int i = 1; i < ids.length; i++) {
					fileIndexService.updateDirectory(new UpdateDirRunnable(
							Integer.parseInt(ids[i]), directoryFileSize));
				}
			}
		} else {// 上传文件到网盘下
			DocDisc docDisc = docDiscService.getById(id);
			docDisc.setFileCount(null == docDisc.getFileCount() ? fileSizes
					.size() : (docDisc.getFileCount() + fileSizes.size()));
			docDisc.setLarge(null == docDisc.getLarge() ? directoryFileSize
					: (docDisc.getLarge() + directoryFileSize));
			fileIndexService.updateDisk(new UpdateDiskRunnable(id,
					directoryFileSize, fileSizes.size()));
		}
	}

	private String getFileName(String path) {
		String fileName = path.substring(path.lastIndexOf("\\") + 1,
				path.length());
		return fileName;
	}

	/**
	 * 获取文件的大小
	 * 
	 * @param fileSize
	 * @return
	 */
	private double getFileLarge(String fileSize) {
		if (fileSize.endsWith(FinalConfig.SIZE_MB)) {
			return new Double(fileSize.replace(FinalConfig.SIZE_MB, ""));
		} else {
			double size = Double.parseDouble(fileSize.replace(
					FinalConfig.SIZE_KB, "")) / 1024;
			return size;
		}
	}

	private String getFilePathInFtp(int id, int type) {
		StringBuilder filePathInFtpString = new StringBuilder();
		if (type == FinalConfig.FILE_IN_DIRECTORY) {
			DocDirectory docDirectory = docDirectoryService.getById(id);
			filePathInFtpString.append(docDirectory.getPath());
			filePathInFtpString.append("/");
			filePathInFtpString.append(docDirectory.getId());
		} else {
			filePathInFtpString.append(id);
		}
		return filePathInFtpString.toString();
	}

	public String getImgClass(String path) {
		String type = path.substring(path.lastIndexOf(".") + 1, path.length());
		switch (type) {
		case "doc":
			return "file_word_ico_d32";
		case "docx":
			return "file_word_ico_d32";
		case "xls":
			return "file_excel_ico_d32";
		case "jpg":
			return "file_photo_ico_d32";
		case "png":
			return "file_photo_ico_d32";
		case "pdf":
			return "file_pdf_ico_d32";
		case "txt":
			return "file_txt_ico_d32";
		default:
			return "file_chm_ico_d32";
		}
	}

	@Override
	public String deleteFiles(List<Integer> fileIds) {
		if (fileIds.size() < 1) {
			return null;
		}
		List<DocFile> files = new ArrayList<DocFile>();
		for (Integer fileId : fileIds) {
			DocFile docFile = getById(fileId);
			files.add(docFile);
			delete(docFile);
		}
		for (DocFile docFile : files) {
			fileMoveService.move(new DeleteFtpFileRunnable(docFile.getPath(),
					docFile.getFileName()));
			// 删除文件对应的索引
			fileIndexService.deleteIndex(new DeleteIndexRunnable(new IndexFile(
					"", docFile.getPath(), docFile.getId().toString(), docFile
							.getHumanName(), ProjectUtils
							.timeStamp2String(docFile.getCreateTime()), docFile
							.getFileName(), "")));
		}
		// updateDirectoryWhenDeleteFiles(files);
		updateParentsDirWhenDeleteFiles(files);
		// TODO 删除文件时 同时更新文件夹所在的文件数和大小
		return null;
	}

	/**
	 * 在文件夹下删除文件时，更新删除文件所在文件夹的文件数和占用大小
	 * 
	 * @param files
	 */
	@SuppressWarnings("unused")
	private void updateDirectoryWhenDeleteFiles(List<DocFile> files) {
		if (files.get(0).getDirectoryId() != null
				&& files.get(0).getDirectoryId() > 0) {
			DocDirectory docDirectory = docDirectoryService.getById(files
					.get(0).getDirectoryId());
			double size = docDirectory.getLarge();
			for (DocFile docFile : files) {
				size = size - docFile.getLarge();
			}
			docDirectory.setLarge(size > 0 ? size : 0);
			int fileCount = (docDirectory.getFileCount() - files.size()) > 0 ? (docDirectory
					.getFileCount() - files.size()) : 0;
			docDirectory.setFileCount(fileCount);
			docDirectoryService.update(docDirectory);
		}
	}

	/**
	 * 删除文件时，更新在这些文件路径上的文件夹和网盘的信息，并且确保更新信息的写操作是线程安全的
	 * 
	 * @param files
	 *            要删除的文件
	 */
	private void updateParentsDirWhenDeleteFiles(List<DocFile> files) {
		double size = 0.0;
		for (DocFile docFile : files) {
			size += null == docFile.getLarge() ? 0 : docFile.getLarge();
		}
		// 删除文件在网盘下
		if (null != files.get(0).getDiskId() && files.get(0).getDiskId() > 0) {
			/*
			 * DocDisc docDisc=docDiscService.getById(files.get(0).getDiskId());
			 * double large=null==docDisc.getLarge()?0:docDisc.getLarge();
			 * docDisc.setLarge(large-size<0?0:(large-size));
			 */
			fileIndexService.updateDisk(new UpdateDiskRunnable(files.get(0)
					.getDiskId(), -size));
		} else {// 删除文件在文件夹下
			String[] pathIds = files.get(0).getPath().split("/");
			/*
			 * DocDisc
			 * docDisc=docDiscService.getById(Integer.parseInt(pathIds[0]));
			 * docDisc
			 * .setLarge(docDisc.getLarge()-size>0?(docDisc.getLarge()-size):0);
			 */
			fileIndexService.updateDisk(new UpdateDiskRunnable(Integer
					.parseInt(pathIds[0]), -size));
			for (int i = 1; i < pathIds.length; i++) {
				if (pathIds.length == i + 1) {
					/*
					 * DocDirectory
					 * docDirectory=docDirectoryService.getById(Integer
					 * .parseInt(pathIds[i]));
					 * docDirectory.setFileCount(docDirectory
					 * .getFileCount()-files.size());
					 * docDirectory.setLarge(docDirectory
					 * .getLarge()-size>0?(docDirectory.getLarge()-size):0);
					 */
					fileIndexService.updateDirectory(new UpdateDirRunnable(
							Integer.parseInt(pathIds[i]), -files.size(), 0,
							-size));
				} else {
					/*
					 * DocDirectory
					 * docDirectory=docDirectoryService.getById(Integer
					 * .parseInt(pathIds[i]));
					 * docDirectory.setLarge(docDirectory
					 * .getLarge()-size>0?(docDirectory.getLarge()-size):0);
					 */
					fileIndexService.updateDirectory(new UpdateDirRunnable(
							Integer.parseInt(pathIds[i]), -size));
				}
			}

		}
	}

	@Override
	public String searchLucene(String param) {
		Searcher searcher;
		try {
			searcher = new Searcher(FinalConfig.index_dir, session);
			List<IndexFile> docFiles = searcher.searchHighlighter("fileName",
					param);
			putSuccess();
			put("docFiles", docFiles);
			searcher.close();
		} catch (IOException e) {
			e.printStackTrace();
			putFalse();
			return getMap();
		} catch (ParseException e) {
			e.printStackTrace();
			putFalse();
			return getMap();
		} catch (InvalidTokenOffsetsException e) {
			e.printStackTrace();
			putFalse();
			return getMap();
		}
		return getMap();
	}

	@Override
	public boolean canDownload(int fileId) {
		int humanId = (int) session.getAttribute(FinalConfig.SESSION_HUMANID);
		int unitId = (int) session
				.getAttribute(FinalConfig.SESSION_HUMAN_UNIT_ID);
		DocFile docFile = getById(fileId);
		if (null == docFile.getDirectoryId() || docFile.getDirectoryId() == 0) {
			return true;
		} else {
			DocDirectory docDirectory = docDirectoryService.getById(docFile
					.getDirectoryId());
			if (docDirectory.getDisplayRange().equals(
					FinalConfig.DirectoryDisplayRange_ALL)) {
				return true;
			}
			if (docDirectory.getDisplayRange().equals(
					FinalConfig.DirectoryDisplayRange_UNIT)
					&& docDirectory.getUnitId() == Integer.parseInt(session
							.getAttribute(FinalConfig.SESSION_HUMAN_UNIT_ID)
							.toString())) {
				return true;
			}
			List<DocDirectoryRange> list = docDirectoryRangeService
					.find("select t from DocDirectoryRange t where t.id.directoryId=?",
							docFile.getDirectoryId());
			for (DocDirectoryRange docDirectoryRange : list) {
				if (docDirectoryRange.getId().getHumanId().equals(humanId))
					return true;
			}
		}
		return false;
	}

	@Override
	public String collectFile(int collectFileId, int directoryId,
			String collectFileType) {
		putSuccess();
		String toPathIds = GetRealPath.getPathIds(directoryId);
		String toPath = GetRealPath.getPath(toPathIds);
		try {
			if (collectFileType.equals(FinalConfig.INDEX_FORM_UPLOAD)) {
				collectFileFromThisSystemFtp(collectFileId, directoryId,
						toPath, toPathIds);
			} else if (collectFileType.equals(FinalConfig.INDEX_FORM_OA)) {
				collectFileFromOa(collectFileId, directoryId, toPath, toPathIds);
			}else if (collectFileType.equals(FinalConfig.INDEX_FROM_BOOK)) {
				
				collectFileFromBook(collectFileId,directoryId,toPath,toPathIds);
			}
		} catch (IOException e) {
			e.printStackTrace();
			putFalse();
			putMessage("文件收藏失败");
		}
		return getMap();
	}

	/**
	 * 收藏来自于本系统内的ftp文件
	 * 
	 * @param collectFileId
	 * @param directoryId
	 * @throws IOException
	 */
	private void collectFileFromThisSystemFtp(int collectFileId,
			int directoryId, String toPath, String toPathIds)
			throws IOException {
		DocFile docFile = getById(collectFileId);
		String fromPath = GetRealPath.getPath(docFile.getPath());
		DocFile collectFile = new DocFile();
		ProjectUtils.objAdapterObjGeneral(collectFile, docFile);
		collectFile.setCreateTime(new Timestamp(System.currentTimeMillis()));
		collectFile.setDirectoryId(directoryId);
		collectFile.setPath(toPathIds);
		collectFile.setId(null);
		collectFile.setDisplayFileName(collectFile.getFileName());
		collectFile.setCollectFrom(FinalConfig.collect_from_docMan);
		save(collectFile);
		FtpUtils.moveFileFromFtp2Ftp(FinalConfig.getDocFtp(), fromPath,
				docFile.getFileName(), FinalConfig.getDocFtp(), toPath,
				docFile.getFileName());
		List<String> docFiles = new ArrayList<String>();
		docFiles.add(collectFile.getLarge().toString());
		updateParentsDirectoryWhenAddFiles(docFiles, directoryId,
				FinalConfig.FILE_IN_DIRECTORY);
	}

	/**
	 * 从OA系统中收藏文件到本系统中，因为OA视图中文件名并不是文件的标题，所以FileName称是文件的实际名字，
	 * displayFileName是标题名字
	 * 
	 * @param collectFileId
	 * @param directoryId
	 * @param toPath
	 * @param toPathIds
	 * @throws IOException
	 */
	private void collectFileFromOa(int collectFileId, int directoryId,
			String toPath, String toPathIds) throws IOException {
		DocFtp oaFtp = FtpUtils.getOaFtp();
		Dangan dangan = danganFromOaService.getById(new BigDecimal(
				collectFileId));
		DocFile collectFileOa = new DocFile();
		collectFileOa.setCreateTime(new Timestamp(System.currentTimeMillis()));
		collectFileOa.setDirectoryId(directoryId);
		collectFileOa.setPath(toPathIds);
		collectFileOa.setFileName(getOaFileName(dangan.getLj()));
		collectFileOa.setHumanId(CastUtil.castInt(session
				.getAttribute(FinalConfig.SESSION_HUMANID)));
		collectFileOa.setHumanName(session.getAttribute(
				FinalConfig.SESSION_HUMANNAME).toString());
		collectFileOa.setDirectoryId(directoryId);
		collectFileOa.setImgClass(FinalConfig.file_type_pdf);
		collectFileOa.setDisplayFileName(dangan.getVlwbt());
		collectFileOa.setCollectFrom(FinalConfig.collect_from_oa);
		getOaFileFtpPath(dangan.getLj());
		getOaFileName(dangan.getLj());
		String fileSize = FtpUtils.moveFileFromFtp2FtpSize(oaFtp,
				getOaFileFtpPath(dangan.getLj()),
				getOaFileName(dangan.getLj()), FinalConfig.getDocFtp(), toPath,
				getOaFileName(dangan.getLj()));
		collectFileOa.setLarge(CastUtil.castDouble(fileSize));
		save(collectFileOa);
		List<String> docFiles = new ArrayList<String>();
		docFiles.add(collectFileOa.getLarge().toString());
		updateParentsDirectoryWhenAddFiles(docFiles, directoryId,
				FinalConfig.FILE_IN_DIRECTORY);
	}
	/**
	 * 
	 * 更新从book来的系统
	 * 
	 * @param collectFileId
	 * @param directoryId
	 * @param toPath
	 * @param toPathIds
	 * @throws IOException
	 */
	private void collectFileFromBook(int collectFileId, int directoryId,
			String toPath, String toPathIds) throws IOException {
		String bookFtpPathPrefix= ProperiesUtils.getProperty("book.path");
		DocBookSon docBookSon=docBookSonService.getById(collectFileId);
		String bookPath=bookFtpPathPrefix+collectFileId+FinalConfig.path_split;
		DocFtp oaFtp = FtpUtils.getOaFtp();
		
		DocFile collectFileOa = new DocFile();
		collectFileOa.setCreateTime(new Timestamp(System.currentTimeMillis()));
		collectFileOa.setDirectoryId(directoryId);
		collectFileOa.setPath(toPathIds);
		collectFileOa.setFileName(docBookSon.getDisplayName());
		collectFileOa.setHumanId(CastUtil.castInt(session
				.getAttribute(FinalConfig.SESSION_HUMANID)));
		collectFileOa.setHumanName(session.getAttribute(
				FinalConfig.SESSION_HUMANNAME).toString());
		collectFileOa.setDirectoryId(directoryId);
		collectFileOa.setImgClass(FinalConfig.file_type_pdf);
		collectFileOa.setDisplayFileName(docBookSon.getSubTitle());
		collectFileOa.setCollectFrom(FinalConfig.collect_from_oa);
		String fileSize = FtpUtils.moveFileFromFtp2FtpSize(FinalConfig.getDocFtp(),
				bookPath,
				docBookSon.getDisplayName(), FinalConfig.getDocFtp(), toPath,
				docBookSon.getDisplayName());
		collectFileOa.setLarge(CastUtil.castDouble(fileSize));
		save(collectFileOa);
		List<String> docFiles = new ArrayList<String>();
		docFiles.add(collectFileOa.getLarge().toString());
		updateParentsDirectoryWhenAddFiles(docFiles, directoryId,
				FinalConfig.FILE_IN_DIRECTORY);
	}
	/**
	 * 获取oa文件的ftp路劲
	 * 
	 * @param lj
	 * @return
	 */
	private String getOaFileFtpPath(String lj) {
		String path = lj.substring(0, lj.lastIndexOf(FinalConfig.path_split));
		return path;
	}

	/**
	 * 获取oa文件的实际文件名
	 * 
	 * @param lj
	 * @return
	 */
	private String getOaFileName(String lj) {
		String fileName = lj.substring(
				lj.lastIndexOf(FinalConfig.path_split) + 1, lj.length());
		return fileName;
	}

	@Override
	public String copyFile(List<Integer> fileIds, int directoryId) {
		DocFile docFile=getById(fileIds.get(0));
		try {
			if(docFile.getDirectoryId()==directoryId){
				putFalse();
				putMessage("该文件夹下已经有该文件存在了");
				return getMap();
			}else {
				DocDirectory docDirectory=docDirectoryService.getById(directoryId);
				String toPath=GetRealPath.getPath(docDirectory.getPath())+FinalConfig.path_split+docDirectory.getName();
				String toPathIds=docDirectory.getPath()+FinalConfig.path_split+directoryId;
				String soursePath=null;
				List<String> fileSizes=new ArrayList<String>();
				boolean is2Update=false;
				for (Integer integer : fileIds) {
					docFile=getById(integer);
					soursePath=GetRealPath.getPath(docFile.getPath());
					if(!FtpUtils.hasFile(FinalConfig.getDocFtp(), toPath, docFile.getFileName())){
						if(FtpUtils.moveFileFromFtp2Ftp(FinalConfig.getDocFtp(), soursePath, docFile.getFileName(),FinalConfig.docFtp, toPath,docFile.getFileName())){
							is2Update=true;
							fileSizes.add(docFile.getLarge().toString()+FinalConfig.SIZE_MB);
							DocFile docFileCopy=new DocFile();
							docFileCopy=(DocFile) ProjectUtils.objAdapterObjGeneral(docFileCopy, docFile);
							docFileCopy.setPath(toPathIds);
							docFileCopy.setDirectoryId(directoryId);
							save(docFileCopy);
						}
					}
				}
				if(is2Update)
					updateParentsDirectoryWhenAddFiles(fileSizes, directoryId,FinalConfig.FILE_IN_DIRECTORY);
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			putFalse();
			putMessage("文件复制时发生错误");
			return getMap();
		}
		putSuccess();
		return getMap();
	}

	@Override
	public String moveFile(List<Integer> fileIds, int directoryId) {

		DocFile docFile = getById(fileIds.get(0));
		try {
			if (docFile.getDirectoryId() == directoryId) {
				putFalse();
				putMessage("该文件夹下已经有该文件存在了");
				return getMap();
			} else {
				DocDirectory docDirectory = docDirectoryService
						.getById(directoryId);
				String toPath = GetRealPath.getPath(docDirectory.getPath())
						+ FinalConfig.path_split + docDirectory.getName();
				String toPathIds = docDirectory.getPath()
						+ FinalConfig.path_split + directoryId;
				String soursePath = null;
				List<DocFile> docFiles=new ArrayList<DocFile>();
				List<String> docFileSizes=new ArrayList<String>();
				boolean is2Update=false;
				for (Integer integer : fileIds) {
					docFile = getById(integer);
					soursePath = GetRealPath.getPath(docFile.getPath());
					if(!FtpUtils.hasFile(FinalConfig.getDocFtp(), toPath, docFile.getFileName())){
						if (FtpUtils.moveFileFromFtp2Ftp(FinalConfig.getDocFtp(),
								soursePath, docFile.getFileName(),
								FinalConfig.getDocFtp(), toPath, docFile.getFileName())) {
							is2Update=true;
							docFileSizes.add(docFile.getLarge()+FinalConfig.SIZE_MB);
							docFiles.add(docFile);
							docFile.setPath(toPathIds);
							docFile.setDirectoryId(directoryId);
							saveOrUpdate(docFile);
							if (!FtpUtils.removeFile(
									FinalConfig.getDocFtp(),
									soursePath + FinalConfig.path_split
											+ docFile.getFileName())) {
								putMessage("文件移动时删除失败");
							}
						}
					}
				}
				if(is2Update){
					updateParentsDirectoryWhenAddFiles(docFileSizes, directoryId, FinalConfig.FILE_IN_DIRECTORY);
					updateParentsDirWhenDeleteFiles(docFiles);
				}
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			putFalse();
			putMessage("文件移动时发生错误");
			return getMap();
		}
		putSuccess();
		return getMap();
	}
}
